let API_URL = "https://125.66.234.97:8443/";
// let API_URL = "http://192.168.0.100:8080/";
const statusBarHeight = uni.getSystemInfoSync().statusBarHeight + "px"; //屏幕顶部间隔
const themeColor = "#1296db";
let requestLodingType = "mask"; //api请求显示的loding类型，mask不可点击，none可点击，一切false类则不显示loding

function getThemeColor() {
  return themeColor;
}
function getStatusBarHeight() {
  return statusBarHeight;
}
if (process.env.NODE_ENV === "development") {
  console.log("开发环境");
  // #ifdef H5
  API_URL = "/api";
  // #endif
} else {
  console.log("生产环境");
}
//高德坐标转百度（传入经度、纬度）
function bd_encrypt(gg_lng, gg_lat) {
  var X_PI = (Math.PI * 3000.0) / 180.0;
  var x = gg_lng,
    y = gg_lat;
  var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * X_PI);
  var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * X_PI);
  var bd_lng = z * Math.cos(theta) + 0.0065;
  var bd_lat = z * Math.sin(theta) + 0.006;
  return {
    latitude: bd_lat,
    longitude: bd_lng,
  };
}

//百度坐标转高德（传入经度、纬度）
function gd_encrypt(bd_lng, bd_lat) {
  var X_PI = (Math.PI * 3000.0) / 180.0;
  var x = bd_lng - 0.0065;
  var y = bd_lat - 0.006;
  var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI);
  var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI);
  var gg_lng = z * Math.cos(theta);
  var gg_lat = z * Math.sin(theta);
  return { longitude: gg_lng + 0.0081, latitude: gg_lat + 0.0021 };
}

//可以0开头的纯数字
function zeroNumber(value) {
  value = value.replace(/[^\d]/g, "");
  return value;
}
//不能输入表情
function noEmoji(value) {
  let ranges = [
    `\ud83c[\udf00-\udfff]`,
    `\ud83d[\udc00-\ude4f]`,
    `\ud83d[\ude80-\udeff]`,
  ];
  value = value.replace(new RegExp(ranges.join("|"), "g"), "");
  return value;
}
function sjc(start, end) {
  let date1 = new Date(start); //开始时间
  let date2 = new Date(end); //结束时间
  let date3 = date2.getTime() - new Date(date1).getTime(); //时间差的毫秒数
  let days = Math.floor(date3 / (24 * 3600 * 1000));

  //计算出小时数
  let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
  let hours = Math.floor(leave1 / (3600 * 1000));
  //计算相差分钟数
  let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数
  let minutes = Math.floor(leave2 / (60 * 1000));
  //计算相差秒数
  let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数
  let seconds = Math.round(leave3 / 1000);
  let text = "";
  if (days) {
    text = text + days + "天 ";
  }
  if (days || hours) {
    text = text + hours + "小时 ";
  }
  if (days || hours || minutes) {
    text = text + minutes + "分钟 ";
  }
  if (days || hours || minutes || seconds) {
    text = text + seconds + " 秒";
  }
  return text;
}
function getDomain() {
  return API_URL;
}
function getApiUrl() {
  return API_URL;
}
function uuid() {
  var s = [];
  var hexDigits = "0123456789abcdef";
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
  }
  s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
  // s[8] = s[13] = s[18] = s[23] = "-";

  var uuid = s.join("");
  return uuid;
}
function fmoney(s, n) {
  n = n > 0 && n <= 20 ? n : 2;

  s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";

  var l = s.split(".")[0].split("").reverse(),
    r = s.split(".")[1];

  var t = "";

  for (var i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
  }

  return t.split("").reverse().join("") + "." + r;
}
// function formatTime(time) {
// 	if (typeof time !== 'number' || time < 0) {
// 		return time
// 	}
//
// 	var hour = parseInt(time / 3600)
// 	time = time % 3600
// 	var minute = parseInt(time / 60)
// 	time = time % 60
// 	var second = time
//
// 	return ([hour, minute, second]).map(function(n) {
// 		n = n.toString()
// 		return n[1] ? n : '0' + n
// 	}).join(':')
// }

function timestampToFormatString(timstamp, format) {
  if (!format) format = "yyyy-MM-dd hh:mm:ss";
  let newDate = new Date();
  newDate.setTime(timstamp * 1000);
  return newDate.format(format);
}

function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null;
  }
  const format = cFormat || "{y}.{m}.{d} {h}:{i}:{s}";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (("" + time).length === 10) time = parseInt(time) * 1000;
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

function formatTime(time, option) {
  time = +time * 1000;
  const d = new Date(time);
  const now = Date.now();

  const diff = (now - d) / 1000;

  if (diff < 30) {
    return "刚刚";
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + "分钟前";
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + "小时前";
  } else if (diff < 3600 * 24 * 2) {
    return "1天前";
  }
  if (option) {
    return parseTime(time, option);
  } else {
    return (
      d.getMonth() +
      1 +
      "月" +
      d.getDate() +
      "日" +
      d.getHours() +
      "时" +
      d.getMinutes() +
      "分"
    );
  }
}

function formatLocation(longitude, latitude) {
  if (typeof longitude === "string" && typeof latitude === "string") {
    longitude = parseFloat(longitude);
    latitude = parseFloat(latitude);
  }

  longitude = longitude.toFixed(2);
  latitude = latitude.toFixed(2);

  return {
    longitude: longitude.toString().split("."),
    latitude: latitude.toString().split("."),
  };
}

Date.prototype.format = function (format) {
  var args = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter
    S: this.getMilliseconds(),
  };
  if (/(y+)/.test(format))
    format = format.replace(
      RegExp.$1,
      (this.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  for (var i in args) {
    var n = args[i];
    if (new RegExp("(" + i + ")").test(format))
      format = format.replace(
        RegExp.$1,
        RegExp.$1.length == 1 ? n : ("00" + n).substr(("" + n).length)
      );
  }
  return format;
};

var dateUtils = {
  UNITS: {
    年: 31557600000,
    月: 2629800000,
    天: 86400000,
    小时: 3600000,
    分钟: 60000,
    秒: 1000,
  },
  humanize: function (milliseconds) {
    var humanize = "";
    for (var key in this.UNITS) {
      if (milliseconds >= this.UNITS[key]) {
        humanize = Math.floor(milliseconds / this.UNITS[key]) + key + "前";
        break;
      }
    }
    return humanize || "刚刚";
  },
  format: function (dateStr) {
    var date = this.parse(dateStr);
    var diff = Date.now() - date.getTime();
    if (diff < this.UNITS["天"]) {
      return this.humanize(diff);
    }
    var _format = function (number) {
      return number < 10 ? "0" + number : number;
    };
    return (
      date.getFullYear() +
      "/" +
      _format(date.getMonth() + 1) +
      "/" +
      _format(date.getDay()) +
      "-" +
      _format(date.getHours()) +
      ":" +
      _format(date.getMinutes())
    );
  },
  parse: function (str) {
    //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
    var a = str.split(/[^0-9]/);
    return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
  },
};
//展示整数变小数
function showDecimal(num, fixed) {
  let numObj = parseFloat(num / 100);
  return parseFloat(numObj.toFixed(fixed || 2));
}

//展示小数变整数
function toInteger(num) {
  let numObj = parseFloat(num);
  return parseInt((numObj * 100).toFixed(2));
}

function isMobile(str) {
  let myreg = /^[1][3-9][0-9]{9}$/;
  if (!myreg.test(str)) {
    return false;
  } else {
    return true;
  }
}

function isCardNo(card) {
  // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
  // var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  var reg =
    /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/;
  if (!reg.test(card)) {
    return false;
  } else {
    return true;
  }
}

function getUserToken() {
  return uni.getStorageSync("token");
}

function ajax(method, data, success, fail) {
  uni.showLoading({
    title: "加载中",
  });
  uni.request({
    url: this.getApiUrl() + method,
    data: data,
    method: "POST",
    header: {
      "content-type": "application/json", //自定义请求头信息
    },
    success: (res) => {
      uni.hideLoading();
      if (200 == res.statusCode && success) success(res);
      else
        uni.showModal({
          title: "提示",
          content: "网络出错，无法访问服务器，请检查网络再试！",
          success: function (res) {
            if (res.confirm) {
              console.log("用户点击确定");
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
    },
    fail: fail,
    complete: () => {
      console.log("complete");
    },
  });
}
function isJSON(str) {
  if (typeof str == "string") {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == "object" && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      console.log("error：" + str + "!!!" + e);
      return false;
    }
  }
}
function isNumber(checkVal) {
  var reg = /^-?[1-9][0-9]?.?[0-9]*$/;
  return reg.test(checkVal);
}
//跳转路由,url为false类默认返回上一页
function goUrl(url) {
  if (url) {
    uni.navigateTo({
      url,
    });
  } else {
    uni.navigateBack({
      delta: 1,
    });
  }
}
function showToast(title, icon = "none", duration = 2000) {
  uni.showToast({
    title,
    icon,
    duration,
  });
}
//返回并刷新上一页  上一页刷新方法请定义为refreshByBack(),接受一个参数对象data
function backToRefreshPrevPage(prevPage, data = null) {
  if (prevPage) {
    let pages = getCurrentPages();
    pages.some((item, index) => {
      let ind = item.route.indexOf(prevPage);
      if (ind > -1) {
        if (index == pages.length - 1) {
          item.$vm.refreshByBack(data);
          return true;
        } else if (index == pages.length - 2) {
          goUrl(0);
          item.$vm.refreshByBack(data);
          return true;
        }
      }
    });
  }
}
//时间转文字格式
function getTimeStr(time) {
  if (typeof time == "string"&&time.indexOf('T')<0) {
    time = time.replace(/-/g, "/");
  }
  time = new Date(time);
  let month = time.getMonth() + 1,
    date = time.getDate(),
    hour = time.getHours(),
    minutes = time.getMinutes(),
    seconds = time.getSeconds();
  return (
    time.getFullYear() +
    "-" +
    (month > 9 ? month : "0" + month) +
    "-" +
    (date > 9 ? date : "0" + date) +
    " " +
    (hour > 9 ? hour : "0" + hour) +
    ":" +
    (minutes > 9 ? minutes : "0" + minutes) +
    ":" +
    (seconds > 9 ? seconds : "0" + seconds)
  );
}
module.exports = {
  backToRefreshPrevPage,
  goUrl,
  showToast,
  getStatusBarHeight,
  getThemeColor,
  requestLodingType,
  formatTime: formatTime,
  parseTime: parseTime,
  timestampToFormatString: timestampToFormatString,
  formatLocation: formatLocation,
  showDecimal: showDecimal,
  toInteger: toInteger,
  isMobile: isMobile,
  isCardNo: isCardNo,
  dateUtils: dateUtils,
  ajax: ajax,
  getUserToken: getUserToken,
  fmoney: fmoney,
  getDomain: getDomain,
  getApiUrl: getApiUrl,
  uuid: uuid,
  isJSON,
  isNumber,
  sjc,
  zeroNumber,
  noEmoji,
  bd_encrypt,
  gd_encrypt,
  getTimeStr
};
